package cn.bigcontainer.alt.meta.extension.impl;

import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import cn.bigcontainer.alt.common.util.WoJsonKit;
import cn.bigcontainer.alt.common.util.WoKit;
import cn.bigcontainer.alt.common.util.WoVelocityKit;
import cn.bigcontainer.alt.meta.dao.MDao;
import cn.bigcontainer.alt.meta.dto.MForm;
import cn.bigcontainer.alt.meta.dto.MViewDto;
import cn.bigcontainer.alt.meta.extension.MFormSubmission;

/**
 * 从应用中获取扩展sql并执行
 * @author jiaod
 *
 */
@Component(MFormSubmission.DEFAULT)
public class SqlFormSubmission implements MFormSubmission {

	@Resource
	private WoVelocityKit velocity;
	
	@Resource
	private MDao dao;
	
	@Override
	public MViewDto before(MViewDto fv, Boolean create) {
		return executeExtensionSql(fv, create, true);
	}

	private MViewDto executeExtensionSql(MViewDto fv, Boolean create, Boolean before) {
		MForm app = (MForm) fv.getApp();
		String extension = app.getExtension(create ? MForm.PARAM_EXT_CREATE_SUBMIT : MForm.PARAM_EXT_UPDATE_SUBMIT);
		if (WoKit.isEmpty(extension)) {
			return null;
		}
		Map<String, String> extensionData = WoJsonKit.readAsType(extension, Map.class);
		String tmplString = extensionData.get(before ? "before" : "after");
		if (WoKit.isEmpty(tmplString)) {
			return null;
		}
		String sql = velocity.parse(tmplString, app.getObject().getRequest());
		dao.update(sql);
		return null;
	}

	@Override
	public void after(MViewDto fv, Boolean create) {
		executeExtensionSql(fv, create, false);
	}

}
